<!DOCTYPE html>
<html>
    <head>
        <title>Reset src after setMediaKeys()</title>
        <script src="encrypted-media-utils.js"></script>
        <script src="../../resources/testharness.js"></script>
        <script src="../../resources/testharnessreport.js"></script>
    </head>
    <body>
        <video></video>
        <script>
            async_test(function(test)
            {
                var mediaKeys;
                var encryptedEventIndex = 0;
                var video = document.querySelector('video');
                assert_not_equals(video, null);

                // Content to be played. These files must be the same format.
                var content = '../content/test-encrypted.webm';
                var alternateContent = '../content/test-encrypted-different-av-keys.webm';

                var onEncrypted = function(event)
                {
                    ++encryptedEventIndex;
                    assert_not_equals(video.mediaKeys, null);
                    assert_true(video.mediaKeys === mediaKeys);

                    // This event is fired once for the audio stream and once
                    // for the video stream each time .src is set.
                    if (encryptedEventIndex == 2) {
                        // Finished first video; set src to a different video.
                        video.src = alternateContent;
                    } else if (encryptedEventIndex == 4) {
                        // Finished second video.
                        test.done();
                    }
                };

                // Create a MediaKeys object and assign it to video.
                navigator.requestMediaKeySystemAccess('org.w3.clearkey', getConfigurationForFile(content))
                .then(function(access) {
                    assert_equals(access.keySystem, 'org.w3.clearkey');
                    return access.createMediaKeys();
                }).then(function(result) {
                    mediaKeys = result;
                    assert_not_equals(mediaKeys, null);
                    return video.setMediaKeys(mediaKeys);
                }).then(function(result) {
                    assert_not_equals(video.mediaKeys, null, 'not set initially');
                    assert_true(video.mediaKeys === mediaKeys);

                    // Set src to a video.
                    waitForEventAndRunStep('encrypted', video, onEncrypted, test);
                    video.src = content;
                }).catch(function(error) {
                    forceTestFailureFromPromise(test, error);
                });
            }, 'Reset src after setMediaKeys().');
        </script>
    </body>
</html>
